package com.security.interceptor;

import com.alibaba.fastjson.JSON;
import com.security.entity.AppInfo;
import com.security.service.AppInfoIService;
import com.security.tools.RedisUtil;
import com.security.vo.RestfulDTO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.MediaType;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

/**
 * Package: com.security.interceptor
 * Description：access_token过滤器
 * Author: huangjian
 * Date:  2020/9/17 10:19
 * Modified By:
 * @author huangjian
 */
@Slf4j
public class InterfaceAuthCheckInterceptor implements HandlerInterceptor {
    @Resource
    private RedisUtil redisUtil;
    @Resource
    private AppInfoIService appInfoIService;

    @Override
    public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3) {

    }

    @Override
    public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3) {

    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object obj)
            throws Exception {
        String access_token = request.getParameter("access_token");
        if (StringUtils.isEmpty(access_token)) {
            writeError(response, "access_token is required");
            return false;
        }
        if (!redisUtil.exists(access_token)) {
            writeError(response, "access_token is valid");
            return false;
        }
        String appId = redisUtil.get(access_token);
        AppInfo appInfo = appInfoIService.getOneByAppId(appId);
        if (Objects.isNull(appInfo)) {
            writeError(response, "access_token is valid");
            return false;
        }
        if (appInfo.getIsDel()) {
            writeError(response, "合作关系未建立");
            return false;
        }
        log.info("access_token校验通过");
        return true;
    }

    private void writeError(HttpServletResponse response, String failMessage) throws IOException {
        log.error(failMessage);
        response.setStatus(HttpServletResponse.SC_OK);
        response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
        response.getWriter().write(JSON.toJSONString(RestfulDTO.fail(failMessage)));
    }
}

